#include"myStdio.h"

FILE_ *fopen(const char* pathname,const char*mode)
{
  int flag=0;
  int defaultMode=0666;
  if(strcmp(mode,"r")==0)
  {
  flag|=O_RDONLY;
  }
  else if(strcmp(mode,"w")==0)
  {
  flag|=(O_WRONLY|O_TRUNC|O_CREAT);
  }
  else if(strcmp(mode,"a")==0)
  {
  flag=(O_WRONLY|O_APPEND|O_CREAT);
  }
  else
  {
  }
  int fd=0;
  if(flag&O_RDONLY) fd=open(pathname,flag);
 else fd=open(pathname,flag,defaultMode);
  if(fd<0)
  { 
  const char* err=strerror(errno);
  write(2,strerror(errno),strlen(err));
  return NULL;
  }
  FILE_* fp=malloc(sizeof(FILE_));
  assert(fp);
  fp->flag=SYNC_LINE;
  fp->fileno=fd;
  fp->cap=SIZE;
  fp->size=0;
  memset(fp->buffer,0,SIZE);
  return fp;
}
void fwrite(void*ptr,int num,FILE_* fp)
{
 memcpy(fp->buffer+fp->size,ptr,num);
 fp->size+=num;
 if(fp->flag&SYNC_NOW)
  {
  write(fp->fileno,fp->buffer,fp->size);  
  fp->size=0;
  }
  else if(fp->flag&SYNC_LINE)
  {
   if(fp->buffer[fp->size-1]=='\n')
    {  
    write(fp->fileno,fp->buffer,fp->size);  
   fp->size=0;
    }
  }
  else if(fp->flag&SYNC_FULL)
  {
  if(fp->size==fp->cap){ 
  write(fp->fileno,fp->buffer,fp->size);
  fp->size=0;
   }
  }
  else
  {
  }
}

void fflush(FILE_* fp)
{
 if(fp->size>0)  write(fp->fileno,fp->buffer,fp->size);
}

void fclose(FILE_ *fp)
{
  fflush(fp);
  close(fp->fileno);
}
